<?php

namespace services\task;

use Yii;
use common\components\Service;
use common\models\member\Attr;
use common\models\member\Member;
use common\models\task\TaskOperateLog;

/**
 * Class TaskOperateLogService
 * @package services\task
 */
class TaskOperateLogService extends Service
{
    /**
     * 任务操作日志列表
     *
     * @param array $params
     * @return array
     */
    public function getTaskLogList(int $taskId = 0): array
    {
        $logList = TaskOperateLog::find()->alias('tol')
            ->select(['tol.*', 'm.realname'])
            ->leftJoin(Member::tableName().' m', 'm.id = tol.operate_id')
            ->where([
                'task_id' => $taskId
            ])
            ->orderBy([
                'created_at' => SORT_DESC,
                'id' => SORT_DESC
            ])
            ->asArray()
            ->all();

        /**
         * @var Attr[] $attrList
         */
        $attrList = Attr::find()
            ->where([
                'member_id' => array_column($logList, 'operate_id'),
                'project_id' => Yii::$app->params['project_id'],
            ])
            ->indexBy('member_id')
            ->all();

        $list = [];
        foreach ($logList as $row) {
            $list[] = [
                'id' => $row['id'],
                'task_id' => $row['task_id'],
                'content' => $row['content'],
                'type' => $row['type'],
                'type_str' => TaskOperateLog::$types[$row['type']] ?? '',
                'realname' => $row['operate_id'] > 0 ? ($row['realname'] ?: '') : '系统消息',
                'profession_name' => $attrList[$row['operate_id']]->profession_name ?? '',
                'created_at_str' => date('Y-m-d H:i', $row['created_at']),
            ];
        }

        return $list;
    }
}
